import Author from "../components/Author";
import Authorteacher from "../components/Author_teacher";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { getCategoryList, getLevelList, getRankList } from "@/api/rule";
import { editPrize, getPrizeDetail } from "@/api/prize";
import {
  ScientificPrizeType,
  SubjectType,
  DefaultSubjectType,
  CompleteUnit,
  SumUnitCnt,
  UnitRank,
  FirstLevelDiscipline,
  ProjectScource,
  ResultsForm
} from "@/utils/variable";

export default {
  name: "PrizeUpdate",
  components: { Author, ElImageViewer, Authorteacher },
  filters: {
    statusFilter(status) {
      const statusMap = {
        未审核: "info",
        通过: "success",
        不通过: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      PDF_vis: false,
      pageNums: 0,
      pdfurl: null,
      activeName: ["check_history"],
      checkHistory: [],
      delete_file_id: [],
      disabled: true,
      isLtSize: false,
      fileData: [], // 保存上传的文件
      sendFormData: new FormData(),
      baseDataFormValidated: false,
      dialogImageUrl: "",
      dialogVisible: false,
      hideupload: true,
      image: "",
      showViewer: false,
      nowImages: [],
      fileList: [],
      fileListBak: [],
      deleteFileId: [],
      departmentList: [],
      author_student: [],
      author_teacher: [],
      // 表单数据
      mediaFormData: {},
      mediaFormDesc: {},
      remarkFormData: {},
      remarkFormDesc: {
        remarks: {
          type: "textarea",
          label: "备注"
        }
      },
      formData: {},
      formDesc: {
        title: {
          type: "input",
          label: "奖励名称",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          }
        },
        results_name: {
          type: "input",
          label: "成果名称",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          }
        },
        scientific_prize_type: {
          type: "select",
          label: "奖励(科研奖励用)类别",
          required: true,
          options: ScientificPrizeType,
          attrs: {
            filterable: true,
            size: "small"
          },
          style: {
            width: "75%"
          }
        },
        people_cnt: {
          type: "number",
          label: "获奖人数",
          required: true,
          attrs: {
            size: "small",
            controls: false
          },
          style: {
            width: "50%"
          },
          layout: 12
        },
        licence_issuing_authority: {
          type: "input",
          label: "发证机关",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        prize_date: {
          type: "date",
          required: true,
          label: "获奖日期",
          attrs: {
            size: "small",
            "value-format": "yyyy-MM-dd"
          },
          style: {
            width: "50%"
          },
          layout: 12
        },
        complete_unit: {
          type: "input",
          label: "完成单位",
          required: true,
          default: CompleteUnit,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        prize_category: {
          type: "select",
          label: "获奖类别",
          required: true,
          options: getCategoryList().then(res => {
            return res;
          }),
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          prop: {
            text: "name",
            value: "id"
          },
          layout: 12
        },
        prize_rank: {
          type: "select",
          label: "获奖等级",
          required: true,
          options: getRankList().then(res => {
            return res;
          }),
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          prop: {
            text: "name",
            value: "id"
          },
          layout: 12
        },
        prize_level: {
          type: "select",
          label: "获奖级别",
          required: true,
          options: getLevelList().then(res => {
            return res;
          }),
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          prop: {
            text: "name",
            value: "id"
          },
          layout: 12
        },
        sum_unit_cnt: {
          type: "select",
          label: "总参加单位数",
          required: false,
          options: SumUnitCnt,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        unit_rank: {
          type: "select",
          label: "单位排名",
          required: false,
          options: UnitRank,
          attrs: {
            size: "small",
            clearable: true
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        authorization_num: {
          type: "input",
          label: "奖励批准号",
          required: true,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        first_level_discipline: {
          type: "select",
          label: "一级学科",
          required: true,
          options: FirstLevelDiscipline,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        project_source: {
          type: "select",
          label: "项目来源",
          required: true,
          options: ProjectScource,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        },
        subject_type: {
          type: "radio",
          label: "学科门类",
          required: true,
          options: SubjectType,
          default: DefaultSubjectType,
          layout: 12
        },
        results_form: {
          type: "select",
          label: "成果形式",
          required: true,
          options: ResultsForm,
          attrs: {
            size: "small"
          },
          style: {
            width: "75%"
          },
          layout: 12
        }
      }
    };
  },
  activated() {
    const id = this.$route.query.id;
    // const id = 12
    if (id) {
      this.id = id;
      this.getData();
    }
  },
  created() {
    const id = this.$route.query.id;
    var from = this.$route.query.from;
    if (!from) {
      from = "MyPrize";
    }
    if (!id) {
      this.$message({
        message: "请点击一个获奖进行修改",
        type: "info",
        duration: 4000
      });
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        name: from
      });
    } else {
      this.id = id;
      this.getData();
      this.from = from;
    }
  },
  mounted() {
    this.init();
  },
  methods: {
    // 获取数据
    getData() {
      getPrizeDetail({ id: this.id }).then(response => {
        this.formData = response;
        let author_student = [];
        let author_teacher = [];
        response.authors.map(i => {
          if (i.author_type.indexOf('学生')>-1 ) {
            author_student.push(i);
          } else {
            author_teacher.push(i);
          }
        });
        this.author_student = author_student;
        this.author_teacher = author_teacher;
        this.formData.reward = [
          response.category,
          response.competition,
          response.institution
        ];
        this.remarkFormData = { remarks: response.remarks };
        this.checkHistory = response.check_history;
        var fileList = response.files.map(i => {
          i.url = i.file;
          return i;
        });
        this.fileList = fileList;
        this.fileListBak = JSON.parse(JSON.stringify(fileList));
      });
    },

    init() {
      this.initData();
      this.addBaseFormCss();
    },
    // 初始化数据
    initData() {
      this.sendFormData = new FormData();
      this.baseDataFormValidated = false;
    },
    // 为基本信息表单添加css
    addBaseFormCss() {
      const form1 = document.getElementById("form1");
      const tmp = form1.childNodes[0].childNodes[0].childNodes[0].childNodes[0];
      var className = tmp.childNodes[0].getAttribute("class") + " first-node";
      tmp.childNodes[0].setAttribute("class", className);
    },

    // 基本信息表单请求前的钩子，阻止请求并把数据添加到结果表单，修改状态为验证通过
    beforeRequestBaseDataForm(data) {
      data.reward = data.reward[2];
      delete data.rank;
      delete data.level;
      delete data.file;
      delete data.file_name;
      delete data.first_check_opinion;
      delete data.first_check_status;
      delete data.money;
      delete data.second_check_status;
      delete data.files;
      delete data.category;
      delete data.competition;
      delete data.authors;
      delete data.institution;

      this.sendFormData.set(
        "delete_file_id",
        JSON.stringify(this.delete_file_id)
      );

      for (var i in data) {
        if (data[i] !== undefined) {
          this.sendFormData.append(i, data[i]);
        }
      }
      this.baseDataFormValidated = true;
      return false;
    },

    // 获取子组件--学生信息 验证后的数据
    getAuthorData(data, v) {
      const jsonData = JSON.stringify(data.authorDataList);
      this.sendFormData.append("author_student", jsonData);
      this.author_student_v = v;
    },

    // 获取子组件--老师信息 验证后的数据
    getAuthorData1(data, v) {
      const jsonData = JSON.stringify(data.authorDataList);
      this.sendFormData.append("author_teacher", jsonData);
      this.author_teacher_v = v;
    },

    async commitAuthorData() {
      await this.$refs.author.commitAuthor();
      await this.$refs.authorteacher.commitAuthor();
      // 数据都通过验证，则进行保存操作
      const file_cnt = this.sendFormData.getAll("file").length+this.$refs.upload.fileList.length;
      if (
        this.baseDataFormValidated &&
        file_cnt > 0 &&
        this.author_teacher_v &&
        this.author_student_v
      ) {
        this.createData();
      }
    },

    // 新建数据(注:需要修改成UpdateData,未改原因:后端未提供修改接口)
    createData() {
      if (this.isLtSize) {
        return false;
      }
      const loading = this.$loading({
        lock: true,
        text: "正在处理",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      editPrize(this.sendFormData.get("id"), this.sendFormData)
        .then(res => {
          loading.close();
          this.$notify.success({
            title: "成功",
            message: res.message,
            duration: 2000
          });
        })
        .catch(res => {
          loading.close();
          this.$notify.error({
            title: "失败",
            message: res.response.data.message,
            duration: 2000
          });
        });
    },

    handlePictureCardPreview(file) {
      this.fileListView = [file.url];
      this.dialogVisible = true;
    },

    closeViewer() {
      this.showViewer = false;
    },
    // 上传文件之前的钩子
    beforeUpload(file) {
      const type = file.name.split(".")[1];
      if (["png", "jpg", "jpeg"].indexOf(type) === -1) {
        this.$message.error("只能上传png,jpg,jpeg格式图片");
        return false;
      }
      // 限制文件上传大小, 大于 maxSize M则提示, 且不请求提交表单
      const maxSize = 5;
      const isLtSize = file.size / 1024 / 1024 >= maxSize;
      this.isLtSize = isLtSize;
      if (isLtSize) {
        this.$message.error("上传的每个文件大小不能超过" + maxSize + "M");
        return false;
      }
    },

    // 文件列表移除文件的钩子
    handleRemoveFile(file, fileList) {
      file.id ? this.delete_file_id.push(file.id) : null;
      this.hideupload = false;
    },

    // 上传文件事件，将文件添加到formdata
    uploadFile(item) {
      this.sendFormData.append("file", item.file);
    },

    // 文件列表改变时的钩子, 添加文件时将文件路径加入预览列表中
    handleChange(file, fileList) {
      this.nowImages.push(file.url);
      this.hideupload = true;
    },
    // 保存备注表单也就是提交包括前面的所有表单
    async beforeRequestRemarkForm(data) {
      this.initData();
    },

    // 保存备注表单事件, 对其它表单进行提交
    async handleRequestRemarkForm(data) {
      await this.$refs.baseDataForm.handleSubmitForm();
      // 在这里加上附件表单的数据，因为baseDataForm里也有附件表单的字段
      for (var key in this.remarkFormData) {
        this.sendFormData.set(key, this.remarkFormData[key]);
      }
      await this.$refs.upload.submit();
      const file_cnt = this.sendFormData.getAll("file").length+this.$refs.upload.fileList.length;
      if (!file_cnt) {
        this.$notify({
          type: "error",
          title: "附件错误",
          message: "附件必须上传",
          duration: 4000
        });
        return;
      }
      this.commitAuthorData();
    },

    // 将当前的页面删除，并跳回到之前的页面
    goToFrom() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({
        name: this.from,
        params: { refresh: true }
      });
    }
  }
};
